package com.vue.vuedemo.interceptor;

import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import com.auth0.jwt.JWT;
import com.vue.vuedemo.annotation.CheckToken;
import com.vue.vuedemo.annotation.LoginToken;
import com.vue.vuedemo.pojo.User;
import com.vue.vuedemo.service.UserService;
import com.vue.vuedemo.util.JwtUtil;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor  {

    @Autowired
    UserService userService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
        //获取http请求头的token
        String token = request.getHeader("token");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type,token"); //set token for request.getHeader("token");
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        if (method.isAnnotationPresent(LoginToken.class)) {
            LoginToken loginToken = method.getAnnotation(LoginToken.class);
            if (loginToken.required()) {
                return true;
            }
        }
        
        
       
        if (method.isAnnotationPresent(CheckToken.class)) {
            CheckToken checkToken = method.getAnnotation(CheckToken.class);
            if (checkToken.required()) {
                if (token == null) {
                	response.setContentType("application/json;charset=UTF-8");
                	
                    PrintWriter out = response.getWriter();
                    out.write("{\"status\":\"-1\",\"message\":\"无token,请重新登陆\"}");
                    out.flush();
                    out.close();
//                    throw new RuntimeException("无token,请重新登陆");
                    return false;
                }
                String username = JWT.decode(token).getClaim("username").asString();
                String password = JWT.decode(token).getClaim("password").asString();
                User user = userService.getUserByUsername(username, password);
                if (user == null) {
                  response.setContentType("application/json;charset=UTF-8");
                  PrintWriter out = response.getWriter();
                  out.write("{\"status\":\"-1\",\"message\":\"无token,请重新登陆\"}");
                  out.flush();
                  out.close();
                	
                  throw new RuntimeException("用户不存在");
                }

                Boolean check = JwtUtil.checkJWT(token, user);
                System.out.println("check +++");
                if (!check) {
                	 response.setContentType("application/json;charset=UTF-8");
                     PrintWriter out = response.getWriter();
                     out.write("{\"status\":\"-1\",\"message\":\"非法\"}");
                     out.flush();
                     out.close();
                    System.out.println("非法");
//                    throw new RuntimeException("非法访问");
                    return false;
                }
                return true;
            }
        }
        return true;
	
	}

	
	
	
}
